package juc.thread_volatile;

/**
 * 可见性测试:
 * volatile:1.保证线程间的可见性，2.防止指令重排序;
 *
 */
public class VisibilityTest {


    private boolean flag = true;
//    private volatile boolean flag = true;

    public void refresh() {
        flag = false;
        System.out.println(Thread.currentThread().getName() + "修改flag");
    }

    public void load() {
        System.out.println(Thread.currentThread().getName() + "开始执行.....");
        int i = 0;
        while (flag) {
            i++;
            //TODO  业务逻辑
//            System.out.println(Thread.currentThread().getName() + "i=" + i);
        }
        System.out.println(Thread.currentThread().getName() + "跳出循环: i=" + i);
    }

    /**
     * 线程A执行时获取的flag=true,而线程B修改flag=false,于线程A来说这个过程不可见。
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        VisibilityTest test = new VisibilityTest();

        // 线程threadA模拟数据加载场景
        Thread threadA = new Thread(() -> test.load(), "threadA");
        threadA.start();

        // 让threadA执行一会儿
        Thread.sleep(500);
        // 线程threadB通过flag控制threadA的执行时间
        Thread threadB = new Thread(() -> test.refresh(), "threadB");
        threadB.start();

    }
}

